import musicList from '@/components/music-list/music-list.vue';
import { procressSongs } from '@/service/song';

export default function createDetailComponent(name, key, fetch) {
  return {
    name,
    components: {
      musicList
    },
    props: {
      data: Object
    },
    computed: {
      computedData() {
        let ret = null;
        const data = this.data;
        // 如果props中有singer信息,则返回props中的singer,没有则使用session中的信息
        if (data) {
          ret = data;
        } else {
          const cached = JSON.parse(sessionStorage.getItem(key));
          // 如果缓存存在,且和路径参数中的id相等,说明是从当前页面刷新的
          if (cached && (cached.mid || cached.id + '') === this.$route.params.id) {
            ret = cached;
          }
        }
        return ret;
      },
      pic() {
        const data = this.computedData;
        return data && data.pic;
      },
      title() {
        const data = this.computedData;
        return data && (data.name || data.title);
      }
    },
    data() {
      return {
        songs: [],
        loading: true
      };
    },
    async created() {
      // 优化,先将响应式数据做缓存,以后每次调用都不会进行依赖收集
      const data = this.computedData;
      // 如果this.computedSinger为null则说明有可能路径参数里的mid被修改过,则不请求数据
      // 退回一级路由
      if (!data) {
        // 获取一级路由
        const path = this.$route.matched[0].path;
        this.$router.push({
          path
        });
        return;
      }
      const result = await fetch(data);
      this.songs = await procressSongs(result.songs);
      this.loading = false;
    }
  };
}
